package com.wf.utils;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mpk
 * @since 2024/8/27 17:52:43
 */

/**
 * 腾讯地图工具类
 *
 * @author mpk
 */
@Slf4j
@Component
public class LocationUtil {


    @Value("${qq.map.key}")
    private String key;

    public Map<String, Double> getLocation(String location) {

        String jsonResponse;
        Map<String, Double> locationMap;
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("key", key);
            map.put("address", location);
            jsonResponse = HttpUtil.get("https://apis.map.qq.com/ws/geocoder/v1", map);


            log.info(jsonResponse);
            // 创建 ObjectMapper 对象
            ObjectMapper objectMapper = new ObjectMapper();

            // 解析 JSON 字符串为 JsonNode 对象
            JsonNode rootNode = objectMapper.readTree(jsonResponse);

            // 获取 location 节点
            JsonNode locationNode = rootNode.path("result").path("location");

            // 将 location 节点封装到 Map 中
            locationMap = new HashMap<>();
            locationMap.put("longitude", locationNode.path("lng").asDouble());
            locationMap.put("latitude", locationNode.path("lat").asDouble());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return locationMap;

    }


}
